package com.gmrz.uap.jfinal.handler;

import com.jfinal.handler.Handler;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SystemContextPathHandler extends Handler {
    private String contextPathName;

    public SystemContextPathHandler() {
        contextPathName = "CONTEXT_PATH";
    }

    public SystemContextPathHandler(String contextPathName) {
        if (StrKit.isBlank(contextPathName)) {
            throw new IllegalArgumentException("contextPathName can not be blank.");
        }
        this.contextPathName = contextPathName;
    }

    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path;
        request.setAttribute(contextPathName, basePath);
        next.handle(target, request, response, isHandled);
    }
}
